﻿using Microsoft.Extensions.Logging;
using ShanNiang.Hosting;
using ShanNiang.Service.Enumerate;
using ShanNiang.Service.Interfaces;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Media;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;

namespace ShanNiang.Service.Implementations
{
    public class SoundService : LocalService, ISoundService
    {
        private readonly SpeechSynthesizer _synthesizer; // = new SpeechSynthesizer();
        private readonly ScanSoundsConfig _scanSoundsConfig;

        private readonly ConcurrentDictionary<string, Stream> SoundDic = new ConcurrentDictionary<string, Stream>();

        public SoundService(ScanSoundsConfig scanSoundsConfig, ILogger<LocalService> logger) : base(logger)
        {
            _scanSoundsConfig = scanSoundsConfig;
            _synthesizer = new SpeechSynthesizer();
            _synthesizer.Volume = 100;  // 音量 (0-100)
            _synthesizer.Rate = 0;      // 语速 (-10 到 10)
            // 选择一个语音（如果有多个安装的语音）
            _synthesizer.SelectVoice("Microsoft Huihui Desktop");

            //foreach (var voice in _synthesizer.GetInstalledVoices())
            //{
            //    logger.LogWarning($"name is {voice.VoiceInfo.Name}, id is {voice.VoiceInfo.Id}");
            //}
            //取得音频输出列表
            //foreach (ISpeechObjectToken AudioOut in speech.GetAudioOutputs(string.Empty, string.Empty))
            //{
            //    cmbAudioOut.Items.Add(AudioOut.GetDescription(49));
            //}

        }

        public void PlayError(CodeType codeType)
        {
            var stream = GetStremAsync(_scanSoundsConfig.ErrorSounds[codeType]);
            if (stream != null)
            {
                stream.Seek(0, SeekOrigin.Begin);
                new SoundPlayer(stream).Play();
            }
        }

        public void PlayInfo(CodeType codeType)
        {
            var stream = GetStremAsync(_scanSoundsConfig.InfoSounds[codeType]);
            if (stream != null)
            {
                stream.Seek(0, SeekOrigin.Begin);
                new SoundPlayer(stream).Play();
            }
        }

        public void PlaySuccess(CodeType codeType)
        {
            var stream = GetStremAsync(_scanSoundsConfig.SuccessSounds[codeType]);
            if (stream != null)
            {
                stream.Seek(0, SeekOrigin.Begin);
                new SoundPlayer(stream).Play();
            }
        }

        public void PlayWanning(CodeType codeType)
        {
            var stream = GetStremAsync(_scanSoundsConfig.WanningSounds[codeType]);
            if (stream != null)
            {
                stream.Seek(0, SeekOrigin.Begin);
                new SoundPlayer(stream).Play();
            }
        }

        public void Speak(string text)
        {
            _synthesizer.Speak(text);

        }

        public Prompt SpeakAsync(string text)
        {
            return _synthesizer.SpeakAsync(text);
        }

        private Stream? GetStremAsync(string fileName)
        {
            if (!string.IsNullOrEmpty(fileName))
            {
                if (!SoundDic.TryGetValue(fileName, out Stream? stream))
                {
                    var path = Path.Combine(Environment.CurrentDirectory, "Sounds", fileName);
                    if (Path.Exists(path))
                    {
                        using (FileStream fileStream = File.OpenRead(path))
                        {
                            MemoryStream memoryStream = new MemoryStream();
                            fileStream.CopyTo(memoryStream);
                            // 使用前可重置流的位置
                            //memoryStream.Position = 0;
                            SoundDic[fileName] = memoryStream;
                        }
                    }
                }
                if (SoundDic.TryGetValue(fileName, out Stream? strm))
                {
                    return strm;
                }
                //return SoundDic[fileName];
            }
            return null;
        }


    }
}
